var map, geocoder, tool, handler;
var zoom = 12;
var currentTag;
let tagMap = new Map();
let tagDataMap = new Map();

//创建地图及控件
function onLoad() {
    //初始化地图对象
    map = new T.Map("mapDiv");
    //设置显示地图的中心点(荆州 dms：112.2397, 30.3252;degrees: 112°14'22.920", 30°19'30.720")和级别12
    map.centerAndZoom(new T.LngLat(112.2397, 30.3252), zoom);
    //允许鼠标滚轮缩放地图
    map.enableScrollWheelZoom();
    //禁止鼠标双击放大地图
    map.disableDoubleClickZoom();

    //创建缩放平移控件对象
    createBigAndSmallControl();

    //添加比例尺控件
    createScale();

    //添加鹰眼地图
    createMiniMap();

    //创建右键菜单对象
    createMenu();

    //创建搜索对象
    createSearchControl();

    //创建画图工具
    createDrawingTools();
}

//添加放大缩小控件，并放到右上角
function createBigAndSmallControl() {
    control = new T.Control.Zoom();
    control.setPosition(T_ANCHOR_TOP_RIGHT);
    map.addControl(control);
}

//添加比例尺控件
function createScale() {
    var scale = new T.Control.Scale();
    map.addControl(scale);
}

//添加鹰眼地图
function createMiniMap() {
    var miniMap = new T.Control.OverviewMap({
        isOpen: true,
        size: new T.Point(150, 150)
    });
    map.addControl(miniMap);
}

//创建右键菜单对象
function createMenu() {
    var menu = new T.ContextMenu({width: 140});
    var txtMenuItem = [
        {
            text: '放大',
            callback: function () {
                map.zoomIn()
            }
        },
        {
            text: '缩小',
            callback: function () {
                map.zoomOut()
            }
        },
        {
            text: '放置到最大级',
            callback: function () {
                map.setZoom(18)
            }
        },
        {
            text: '查看全国',
            callback: function () {
                map.setZoom(4)
            }
        },
        {
            text: '获得右键点击处坐标',
            isDisable: false,
            callback: function (lnglat) {
                alert(lnglat.getLng().toFixed(5) + "," + lnglat.getLat().toFixed(5));
            }
        }
    ];

    for (var i = 0; i < txtMenuItem.length; i++) {
        //添加菜单项
        var item = new T.MenuItem(txtMenuItem[i].text, txtMenuItem[i].callback);
        //item.disable();
        menu.addItem(item);
        if (i == 1 || i == 3) {
            //添加分割线
            menu.addSeparator();
        }
    }
    map.addContextMenu(menu);
}

//创建搜索对象
function createSearchControl() {
    geocoder = new T.Geocoder();
}

//按输入的经纬度定位
function setCenterAndZoom() {
    var lng = document.getElementById("lng").value;
    var lat = document.getElementById("lat").value;
    map.centerAndZoom(new T.LngLat(lng, lat), zoom);
}

//按输入的文本搜索
function search() {
    map.clearOverLays();
    geocoder.getPoint(document.getElementById("keyWord").value, searchResult);
}

function searchResult(result) {
    if (result.getStatus() == 0) {
        map.panTo(result.getLocationPoint(), 12);
        //创建标注对象
        // var marker = new T.Marker(result.getLocationPoint());
        //向地图上添加标注
        // map.addOverLay(marker);
    } else {
        alert(result.getMsg());
    }
}

//点击获取坐标
function addMapClick() {
    removeMapClick();
    map.addEventListener("click", MapClick);

    //开启坐标显示
    map.addEventListener("mousemove", MapMousemove);

    //设置按钮颜色
    document.getElementById("pointButton").classList.remove("btn-info");
    document.getElementById("pointButton").classList.add("btn-warning");
}

function removeMapClick() {
    map.removeEventListener("click", MapClick);
    map.removeEventListener("mousemove", MapMousemove);

    //设置按钮颜色
    document.getElementById("pointButton").classList.remove("btn-warning");
    document.getElementById("pointButton").classList.add("btn-info");
}

function MapClick(e) {
    MapMousemove(e);
    removeMapClick();
}

function MapMousemove(e) {
    $("#lng").val(e.lnglat.getLng().toFixed(5));
    $("#lat").val(e.lnglat.getLat().toFixed(5));
}

//小数转换为度分秒
function convertToDMS(degrees) {
    // 度数的整数部分
    var d = Math.floor(degrees);

    // 度数的小数部分转换为分钟
    var m = (degrees - d) * 60;

    // 分钟的整数部分
    var mi = Math.floor(m);

    // 分钟的小数部分转换为秒
    var s = (m - mi) * 60;

    // 将秒数四舍五入到3位小数
    s = s.toFixed(3);

    // 返回DMS格式
    return d + "°" + mi + "'" + s + "\"";
}

//度分秒转换为小数
function convertFromDMS(dms) {
    // 将输入字符串分割为度、分、秒
    var parts = dms.match(/(\d+)°\s*(\d+)'\s*(\d+(?:\.\d+)?)"/);
    if (parts) {
        var degrees = parseInt(parts[1], 10);
        var minutes = parseInt(parts[2], 10);
        var seconds = parseFloat(parts[3]);

        // 将分和秒转换为十进制度数，并加到度数上
        var decimalDegrees = degrees + minutes / 60 + seconds / 3600;
        return decimalDegrees;
    } else {
        throw new Error('Invalid DMS format');
    }
}

//创建画图工具
function createDrawingTools() {
    tool = new T.Control({position: T_ANCHOR_TOP_LEFT});
    tool.onAdd = function () {
        //标记工具
        var pointContainer = createContainer();
        this.pointButton = createButton("标记工具", "point tool", pointContainer);
        this.pointButton.onclick = openMarkerTool;

        //线段工具
        var lineContainer = createContainer();
        pointContainer.append(lineContainer);
        this.lineButton = createButton("线段工具", "line tool", lineContainer);
        this.lineButton.onclick = openPolylineTool;

        //多边形工具
        var polygonContainer = createContainer();
        pointContainer.append(polygonContainer);
        this.polygonButton = createButton("多边形工具", "polygon tool", polygonContainer);
        this.polygonButton.onclick = openPolygonTool;

        //圆形工具
        var circleContainer = createContainer();
        pointContainer.append(circleContainer);
        this.circleButton = createButton("圆形工具", "circle tool", circleContainer);
        this.circleButton.onclick = openCircleTool;

        //清除所有
        var cleanContainer = createContainer();
        pointContainer.append(cleanContainer);
        this.cleanButton = createButton("清除所有", "clean all", cleanContainer);
        this.cleanButton.onclick = clearAll;

        return pointContainer;
    };

    tool.onRemove = function () {
        //移除控件时要释放
        delete this.pointButton;
        delete this.lineButton;
        delete this.polygonButton;
        delete this.circleButton;
        delete this.cleanButton;
    }

    map.addControl(tool);
}

function createContainer() {
    var container = document.createElement("div");
    container.style.width = "100px";
    return container;
}

function createButton(html, title, container) {
    var button = document.createElement("button");
    if (container) {
        container.appendChild(button);
    }
    button.innerHTML = html;
    button.title = title;
    button.type = "button";
    button.className = "btn btn-default btn-sm";
    button.style.width = "100%";
    return button;
}

/*
 * 操作事件function-----------------------------
 */

//画图工具调用方法
function openMarkerTool() {
    if (handler) handler.close();
    handler = new T.MarkTool(map, {follow: true});
    handler.open();
    handler.addEventListener("mouseup", addMarkerListener)
}

function addMarkerListener(e) {
    //缓存创建的标记
    var tagKey = e.currentMarker.getLngLat().getLng().toFixed(5) + "," + e.currentMarker.getLngLat().getLat().toFixed(5);
    tagMap.set(tagKey, e.currentMarker);
    console.log("缓存创建的标记tagKey: " + tagKey);

    e.currentMarker.addEventListener("mouseover", showTips);
    e.currentMarker.addEventListener("mouseout", closeTips);
    e.currentMarker.addEventListener("dblclick", showInfo);
}

function openPolylineTool() {
    if (handler) handler.close();
    var config = {
        showLabel: true
    };
    handler = new T.PolylineTool(map, config);
    handler.open();
    handler.addEventListener("draw", addPolylineListener)
}

function addPolylineListener(e) {
    console.log("增加线段监听")
    e.currentPolyline.addEventListener("mouseover", showTips);
    e.currentPolyline.addEventListener("mouseout", closeTips);
    e.currentPolyline.addEventListener("dblclick", showInfo);
}

function openPolygonTool() {
    if (handler) handler.close();
    var config = {
        showLabel: true
    };
    handler = new T.PolygonTool(map, config);
    handler.open();
    handler.addEventListener("draw", addPolygonListener)
}

function addPolygonListener(e) {
    e.currentPolygon.addEventListener("mouseover", showTips);
    e.currentPolygon.addEventListener("mouseout", closeTips);
    e.currentPolygon.addEventListener("dblclick", showInfo);
}

function openCircleTool() {
    if (handler) handler.close();
    handler = new T.CircleTool(map, {follow: true});
    handler.open();
    handler.addEventListener("drawend", addCircleListener)
}

function addCircleListener(e) {
    e.currentCircle.addEventListener("mouseover", showTips);
    e.currentCircle.addEventListener("mouseout", closeTips);
    e.currentCircle.addEventListener("dblclick", showInfo);
}

function clearAll() {
    if (confirm("确定要清除所有标记吗？")) {
        map.clearOverLays();
    }
}

//标记详情-------------------
//初始化日历控件
$(".form_datetime").datetimepicker({
    format: "yyyy/mm/dd",
    minView: 2,//这个可以设置最小时间：0分钟；1小时；2天；3月；4年
    maxView: 4,
    startView: 2,
    autoclose: true,
    todayBtn: true,
    clearBtn: true,
    datepicker: false,
    language: 'zh-CN',
    pickerPosition: "bottom-left"
});

function isOverDate(dateInput) {
    const inputDate = new Date(dateInput);
    const today = new Date();
    const threeYearsAgo = new Date(today.getFullYear() - 3, today.getMonth(), today.getDate());

    if (inputDate && inputDate >= threeYearsAgo) {
        // 日期在三年之内
        return false;
    } else {
        // 日期超过三年
        return true;
    }
}

function setinfo(tagData) {
    if (tagData) {
        $("#projectName").val(tagData.projectName);
        $("#projectNumber").val(tagData.projectNumber);
        $("#testOrganize").val(tagData.testOrganize);
        $("#testTime").val(tagData.testTime);
        $("#envType").val(tagData.envType.split(','));
        $('#envType').selectpicker('val', tagData.envType.split(','));
        $("#testPointName").val(tagData.testPointName);
        $("#testPointLng").val(convertToDMS(tagData.testPointLng));
        $("#testPointLat").val(convertToDMS(tagData.testPointLat));
        $("#testItem").val(tagData.testItem);
        $("#testValue").val(tagData.testValue);
        $("#dailyValue").val(tagData.dailyValue);
        $("#protectLevel").val(tagData.protectLevel);
        $("#status").val(tagData.status);
        $("#overTimes").val(tagData.overTimes);
    } else {
        $("#projectName").val("");
        $("#projectNumber").val("");
        $("#testOrganize").val("");
        $("#testTime").val("");
        $("#envType").val([]);
        $('#envType').selectpicker('val', []);
        $("#testPointName").val("");
        $("#testPointLng").val(convertToDMS(currentTag.getLngLat().getLng().toFixed(5)));
        $("#testPointLat").val(convertToDMS(currentTag.getLngLat().getLat().toFixed(5)));
        $("#testItem").val("");
        $("#testValue").val("");
        $("#dailyValue").val("");
        $("#protectLevel").val("");
        $("#status").val("");
        $("#overTimes").val("");
    }
}

//获取当前tag数据
function getCurrentTagType() {
    var tagType;
    if (currentTag instanceof T.Polyline) {
        tagType = 2;
    } else if (currentTag instanceof T.Polygon) {
        tagType = 3;
    } else if (currentTag instanceof T.Circle) {
        tagType = 4;
    } else {
        tagType = 1;
    }
    return tagType;
}

function getCurrentTagKey() {
    var tagKey;
    if (currentTag) {
        tagKey = currentTag.getLngLat().getLng().toFixed(5) + "," + currentTag.getLngLat().getLat().toFixed(5);
    }
    return tagKey;
}

function closeinfo() {
    $('#envDialog').modal('hide');
    setinfo();
}

function saveinfo() {
    //判断是否信息填写完整
    var projectName = $("#projectName").val();
    var projectNumber = $("#projectNumber").val();
    var testOrganize = $("#testOrganize").val();
    var testTime = $("#testTime").val();
    var envType = $("#envType").val();
    var testPointName = $("#testPointName").val();
    var testPointLng = $("#testPointLng").val();
    var testPointLat = $("#testPointLat").val();
    if (projectName == "" || projectNumber == "" || testOrganize == "" || testTime == ""
        || envType == null || testPointName == "" || testPointLng == "" || testPointLat == "") {
        alert("请将左列填写完整！")
        return;
    }
    var testItem = $("#testItem").val();
    var testValue = $("#testValue").val();
    var dailyValue = $("#dailyValue").val();
    var protectLevel = $("#protectLevel").val();
    var status = $("#status").val();
    var overTimes = $("#overTimes").val();

    //判断标记类型
    var tagType = getCurrentTagType();

    $.ajax({
        type: "POST"
        , url: "/mlp/tagdata"
        , data: JSON.stringify({
            projectName: projectName
            , projectNumber: projectNumber
            , testOrganize: testOrganize
            , testTime: testTime
            , envType: envType.join()
            , testPointName: testPointName
            , testPointLng: currentTag.getLngLat().getLng().toFixed(5)
            , testPointLat: currentTag.getLngLat().getLat().toFixed(5)
            , testItem: testItem
            , testValue: testValue
            , dailyValue: dailyValue
            , protectLevel: protectLevel
            , status: status
            , overTimes: overTimes
            , tagType: tagType
        })
        , contentType: "application/json;charset=utf-8;"
        , dataType: "json"
        , cache: false
        , success: function (data) {
            if (data.resultCode == 'SUCCESS') {
                var tagData = data.tagdata;
                var tagKey = tagData.testPointLng + "," + tagData.testPointLat;
                console.log("save tagdata: tagKey" + tagKey);
                tagDataMap.set(tagKey, tagData);

                // 刷新tag
                map.removeOverLay(currentTag);
                var marker = new T.Marker(new T.LngLat(tagData.testPointLng, tagData.testPointLat));
                map.addOverLay(marker);
                tagMap.set(tagKey, marker);
                marker.addEventListener("mouseover", showTips);
                marker.addEventListener("mouseout", closeTips);
                marker.addEventListener("dblclick", showInfo);
                closeinfo();
            } else {
                alert(data.resultMessage);
            }
        }
        , error: function (XMLHttpRequest, textStatus, errorThrown) {
            //alert(XMLHttpRequest.status + textStatus);
        }
    });
}

function deleteinfo() {
    //删除当前tag
    if (currentTag && confirm("确定删除当前标记？")) {
        $.ajax({
            type: "POST"
            , url: "/mlp/tagdata/deleteByLngLat"
            , data: {
                lng: currentTag.getLngLat().getLng().toFixed(5),
                lat: currentTag.getLngLat().getLat().toFixed(5)
            }
            , contentType: "application/x-www-form-urlencoded;charset=utf-8;"
            , dataType: "json"
            , cache: false
            , success: function (data) {
                if (data.resultCode == 'SUCCESS') {
                    var tagKey = getCurrentTagKey();
                    tagMap.delete(tagKey);
                    map.removeOverLay(currentTag);
                    currentTag == null;
                    console.log("删除缓存的标记tagKey: " + tagKey);
                    $('#envDialog').modal('hide');

                    alert("删除成功!");
                } else {
                    alert(data.resultMessage);
                }
            }
            , error: function (XMLHttpRequest, textStatus, errorThrown) {
                //alert(XMLHttpRequest.status + textStatus);
            }
        });
    }
}

//标记详情方法
function showTips(e) {
    currentTag = e.target;
    // 先从缓存拿
    var tagKey = getCurrentTagKey();
    console.log("打开缓存的标记tagKey: " + tagKey);
    var tagdata = tagDataMap.get(tagKey);
    if (tagdata) {
        console.log("从缓存获取弹窗内容")
        createTipByTagData(e.target, tagdata);
        return;
    }

    $.ajax({
        type: "POST"
        , async: false // 设置为同步请求
        , url: "/mlp/tagdata/getByLngLat"
        , data: {
            lng: currentTag.getLngLat().getLng().toFixed(5),
            lat: currentTag.getLngLat().getLat().toFixed(5)
        }
        , contentType: "application/x-www-form-urlencoded;charset=utf-8;"
        , dataType: "json"
        , cache: false
        , success: function (data) {
            createTipByTagData(e.target, data.tagdata);
        }
        , error: function (XMLHttpRequest, textStatus, errorThrown) {
            //alert(XMLHttpRequest.status + textStatus);
        }
    });
}

function createTipByTagData(target, tagData) {
    var sContent = "<div class='bg-danger'><h6>待编辑</h6></div>";
    if (tagData) {
        sContent = "<div>";
        var timeStyle = "<h6>";
        var danger = isOverDate(tagData.testTime);
        if (danger) {
            timeStyle = "<h6 style='color: red'>";
        }
        var statusStyle = "<h6>";
        var overTimeCotent = "";
        if ("超标" == tagData.status) {
            statusStyle = "<h6 style='color: red'>";
            overTimeCotent = "<h6 style='color: red'>超标倍数: " + tagData.overTimes + "</h6>";
        }

        sContent += "<h6>检测点名称: " + tagData.testPointName + "</h6>" +
            timeStyle + "采样时间: " + tagData.testTime + "</h6>" +
            "<h6>环境要素: " + turnToEnv(tagData.envType) + "</h6>" +
            statusStyle + "超标情况: " + tagData.status + "</h6>" + overTimeCotent +
            "</div>";
    }
    var markerInfoWin = new T.InfoWindow();
    markerInfoWin.setContent(sContent);
    target.openInfoWindow(markerInfoWin);
}

//1大气；2地表水；3地下水；4土壤（建设项目）；5土壤（农用地）；
function turnToEnv(envType) {
    console.log("envType: " + envType);
    let str = "";
    if (envType) {
        let envTypes = envType.split(',');
        for (const type of envTypes) {
            switch (type) {
                case "1":
                    str += "大气,";
                    break;
                case "2":
                    str += "地表水,";
                    break;
                case "3":
                    str += "地下水,";
                    break;
                case "4":
                    str += "土壤（建设项目）,";
                    break;
                case "5":
                    str += "土壤（农用地）,";
                    break;
                default:
                    str = ",";
                    break
            }
        }
    }
    console.log("str: " + str);
    if (str.length > 0) {
        str = str.substring(0, str.length - 1);
    }
    console.log("str: " + str);
    return str;
}

function closeTips(e) {
    e.target.closeInfoWindow();
}

function showInfo(e) {
    currentTag = e.target;

    // 先从缓存拿
    var tagKey = getCurrentTagKey();
    console.log("打开缓存的标记tagKey: " + tagKey);
    var tagdata = tagDataMap.get(tagKey);
    if (tagdata) {
        setinfo(tagdata);
        $('#envDialog').modal('show');
        return;
    }

    $.ajax({
        type: "POST"
        , async: false // 设置为同步请求
        , url: "/mlp/tagdata/getByLngLat"
        , data: {
            lng: currentTag.getLngLat().getLng().toFixed(5),
            lat: currentTag.getLngLat().getLat().toFixed(5)
        }
        , contentType: "application/x-www-form-urlencoded;charset=utf-8;"
        , dataType: "json"
        , cache: false
        , success: function (data) {
            if (data.resultCode == 'SUCCESS') {
                var tagData = data.tagdata;
            }
            setinfo(tagData);
            $('#envDialog').modal('show');
        }
        , error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert(XMLHttpRequest.status + textStatus);
        }
    });
}

//后台调用方法
function loadAllTags() {
    removeAllTags();
    //根据环境要素筛选
    var envType = $("#envTypeFilter").val();
    $.ajax({
        type: "POST"
        , url: "/mlp/tagdata/list"
        , data: {
            envType: envType.join()
        }
        , contentType: "application/x-www-form-urlencoded;charset=utf-8;"
        , dataType: "json"
        , cache: false
        , success: function (data) {
            if (data.resultCode == 'SUCCESS') {
                var tagDataList = data.list;
                for (var tagData of tagDataList) {
                    var tagKey = tagData.testPointLng + "," + tagData.testPointLat;
                    console.log("load: tagKey" + tagKey);

                    //向地图上添加标注
                    var marker = new T.Marker(new T.LngLat(tagData.testPointLng, tagData.testPointLat));
                    map.addOverLay(marker);
                    tagDataMap.set(tagKey, tagData);
                    tagMap.set(tagKey, marker);
                    marker.addEventListener("mouseover", showTips);
                    marker.addEventListener("mouseout", closeTips);
                    marker.addEventListener("dblclick", showInfo);
                }
            } else {
                alert(data.resultMessage);
            }
        }
        , error: function (XMLHttpRequest, textStatus, errorThrown) {
            //alert(XMLHttpRequest.status + textStatus);
        }
    });
}

function removeAllTags() {
    for (const [tagKey, marker] of tagMap) {
        map.removeOverLay(marker);
    }
    tagMap.clear();
    tagDataMap.clear();
}
